package hc.springmvcdemo;

import javax.servlet.ServletContext;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import jm.easyconfig.CfgContextEnvironmentAware;
import jm.easyconfig.CfgContextUser;

@Configuration
public class HomeConfiguration {
	@Bean
	public DataSource dataSource() {
		DriverManagerDataSource ds = new org.springframework.jdbc.datasource.DriverManagerDataSource();
		ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
		ds.setUrl("jdbc:mysql://localhost:3306/test");
		ds.setUsername("root");
		ds.setPassword("");
		return ds;
	}
	
	
	@Bean
	CfgContextEnvironmentAware cfgContextEnvironmentAware() {
		return new CfgContextEnvironmentAware();
	}

//	@Bean
//	public ServletRegistrationBean<CfgAdminServlet> cfgAdminServlet() {
//		ServletRegistrationBean<CfgAdminServlet> registrationBean = new ServletRegistrationBean<CfgAdminServlet>(
//				new CfgAdminServlet(), "/easyconfig-admin/*");
//		registrationBean.setName("easyconfig-admin");
//		return registrationBean;
//	}

	@Autowired
	ApplicationContext applicationContext;
	
	@Bean
	public CfgContextUser currentUser() {
		return new CfgContextUser() {
			@Override
			public String getUser() {
				ServletContext servletContext = applicationContext.getBean(ServletContext.class);
				Object user = servletContext.getAttribute("user");
				return user == null ? "" : user.toString();
			}
		};

	}
}
